<?php

namespace addon\lian\model\core\settle;

use addon\fenxiao\model\FenxiaoAccount;
use addon\lian\model\Config;
use addon\lian\model\sqlmodel\LianRewardModel;
use addon\lian\model\core\member\CoreLianMemberAttrService;
use addon\lian\model\core\order\CoreLianRewardAttrService;
use addon\lian\model\core\settle\CoreLianSettleAttrService;
use app\dict\member_account\AccountDict;
use app\model\member\MemberAccount;
use app\service\core\member\CoreMemberAccountService;
use think\facade\Log;
use think\facade\Db;

class CoreLianSettleService
{   
    public function handleQueue($reward_ids){
        Log::info('=========链动2+1结算=====handleQueue====');
        try{
            $reward_list = (new LianRewardModel())->where('id', 'in', $reward_ids)->where('status', 1)->select(); 
            if (empty($reward_list)) {
                return;
            }
            
            // 按结算方式分类处理
            $payRewards = (new CoreLianSettleAttrService())->getRewardListAfterPay($reward_ids);
            $finishRewards = (new CoreLianSettleAttrService())->getRewardListAfterFinish($reward_ids);
            
            // 处理支付后结算的奖励
            foreach($payRewards as $reward){
                $this->processSettlement($reward, true);
            }
            
            // 处理订单完成后结算的奖励
            foreach($finishRewards as $reward){
                $this->processSettlement($reward, false);
            }
        }catch(\Exception $e){
            Log::error('链动2+1结算=====handleQueue====异常: ' . $e->getMessage() . '--file:' . $e->getFile() . '--line:' . $e->getLine());
        }
        
    }
    
    /**
     * 处理单个奖励的结算
     * @param array $reward 奖励数据
     * @param bool $isPay 是否是支付后结算，否则为完成订单后结算
     */
    private function processSettlement($reward, $isPay = true)
    {
        $site_id = $reward['site_id'];
        
        // 获取该奖励站点的配置
        $config = (new Config())->getLianBasicsConfig($site_id);
        $config = $config['data']['value'];
        
        $account_type = (new CoreLianRewardAttrService())->getTakeType($site_id);
        $reward_type = (new CoreLianRewardAttrService())->getRewardType($site_id, $reward['id']);
        
        $current_time = time();
        $start_time = $current_time - ($config['settle_cycle'] * 86400);
        
        $shouldSettle = false;
        $logMessage = '';
        
        if ($config['settle_cycle'] == 0) {
            // 立即结算
            $shouldSettle = true;
            $logMessage = "站点{$site_id}：立即结算处理";
        } else {
            // 周期结算
            $compareTime = $isPay ? strtotime($reward['pay_time']) : strtotime($reward['finish_time']);
            $timeType = $isPay ? '支付时间' : '完成时间';
            if ($compareTime <= $start_time) {
                $shouldSettle = true;
                $logMessage = "站点{$site_id}：周期结算处理，{$timeType}：" . date('Y-m-d H:i:s', $compareTime) . 
                              "，结算起始时间：" . date('Y-m-d H:i:s', $start_time);
            }
        }
        
        if ($shouldSettle) {
            Log::write('======ly_lian======= ' . $logMessage);
            
            // 更新奖励状态为已结算
            $data = [
                'id' => $reward['id'],
                'status' => 2,
                'settle_time' => time()
            ];
            (new LianRewardModel())->update($data);
            
            // 计算实际发放金额
            $giveAmount = $reward['give_amount'] - $reward['frozen_amount'];
            
            // 发放收益到会员账户
            // (new CoreMemberAccountService())->addLog(
            //     $site_id, 
            //     $reward['member_id'], 
            //     $account_type, 
            //     $giveAmount, 
            //     'ly_lian', 
            //     $reward_type
            // );
            $this->sendAccount($site_id, $reward['member_id'], $account_type, $giveAmount, $reward_type);
            
            // 累加会员的已发放金额
            (new CoreLianMemberAttrService())->incGiveCommission(
                $site_id, 
                $reward['member_id'], 
                $giveAmount
            );
        }
    }


    public function sendAccount($site_id, $member_id, $account_type, $giveAmount, $reward_type){
        $member_account = new MemberAccount();
        $commission_account = new FenxiaoAccount();
        $fenxiao = Db::name('fenxiao')->where('site_id', $site_id)->where('member_id', $member_id)->find();
        switch($account_type){
            case 'money':
                $member_account->addMemberAccount($site_id, $member_id, AccountDict::balance_money, $giveAmount, 'lian', 0, $reward_type );
                break;
            case 'commission':
                $commission_account->addAccount($fenxiao['fenxiao_id'], $fenxiao['fenxiao_name'], 'order', $giveAmount, $reward_type);
                break;
            case 'score':
                $member_account->addMemberAccount($site_id, $member_id, AccountDict::point, $giveAmount, 'lian', 0,  $reward_type);
                break;
        }
    }


    public function send($site_id, $list){
        $account_type = (new CoreLianRewardAttrService())->getTakeType($site_id);
        if(empty($list)){  
            return;  
        }
        foreach ($list as $item) {
            $data = [
                'id' => $item['id'],
                'status' => 2,
                'settle_time' => time()
            ];
            (new LianRewardModel())->update($data); // 更新奖励状态为已结算。
    
            $reward_type = (new CoreLianRewardAttrService())->getRewardType($site_id, $item['id']); //获取奖励的奖励类型，直推奖，见点奖等
            Log::write('======ly_lian=======$reward_type:'.$reward_type);
            //发放收益到会员账户
            (new CoreMemberAccountService())->addLog($site_id, $item['member_id'], $account_type, $item['give_amount'], 'ly_lian', $reward_type);
        }
        
    }

       
}